// pages/order_refund_afterSales/index.js
import {
    getNavigationbar
} from "../../api/index.js"
import {
    ReIndex
} from "../../api/order.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scrollViewHeight: 0,
        orderList: [],
        orderListMian: false,
        steps: [],
        currentPage:1
    },
    handleScrollToLower() {
        console.log('触发到底部提示打印');

        let data = {

            currentPage: this.data.currentPage + 1,
            counts: 10,
        }
        this.setData({
            currentPage: this.data.currentPage + 1,
            loading: true
        });
        this.getAfterSales(this.data.currentPage);

    },
    /**
     * 返回回调函数方法
     */
    onClickLeft() {
        wx.navigateBack({
            delta: 1
        })
    },

    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        wx.getSystemInfo({
            success: function (res) {
                const windowHeight = res.windowHeight + 70;
                console.log('手机屏幕高度：', windowHeight);

                // 进行适配操作，例如设置元素高度为屏幕高度的一半
                const halfScreenHeight = windowHeight / 2;
                console.log('屏幕高度的一半：', halfScreenHeight);
                that.setData({
                    scrollViewHeight: windowHeight - 70
                })
            }
        });
    },
    getTiem(updateTimestamp) {
        // 原始时间戳（秒级）  
        let originalTimestamp = updateTimestamp;

        // 将秒级时间戳转换为毫秒级时间戳  
        let originalTimestampMilliseconds = originalTimestamp * 1000;

        // 一天的毫秒数  
        let oneDayInMilliseconds = 24 * 60 * 60 * 1000;

        // 三天的毫秒数  
        let threeDaysInMilliseconds = oneDayInMilliseconds * 3;

        // 计算三天后的时间戳（毫秒级）  
        let timestampAfterThreeDays = originalTimestampMilliseconds + threeDaysInMilliseconds;

        // 如果需要，可以将毫秒级时间戳转换回秒级时间戳  
        let timestampAfterThreeDaysInSeconds = Math.floor(timestampAfterThreeDays / 1000);
        return timestampAfterThreeDaysInSeconds
        // 输出结果  
        console.log('三天后的时间戳（毫秒级）：', timestampAfterThreeDays);
        console.log('三天后的时间戳（秒级）：', timestampAfterThreeDaysInSeconds);
    },
    calculateTimeDifference(systemTimestamp, updateTimestamp) {
        console.log('时间-------------', systemTimestamp, updateTimestamp)
        const timeDiff = this.getTiem(updateTimestamp) - systemTimestamp; // 计算时间差
        console.log('---------------', timeDiff)
        const days = Math.floor(timeDiff / (3 * 24 * 60 * 60)); // 计算天数
        const hours = Math.floor((timeDiff % (24 * 60 * 60)) / 3600); // 计算小时数
        const minutes = Math.floor((timeDiff % 3600) / 60); // 计算分钟数

        const cmps = {
            day: days,
            hour: hours,
            minute: minutes
        };

        if (cmps.day != null && cmps.day > 0) {
            return `${cmps.day}天${cmps.hour ?? 0}时${cmps.minute ?? 0}分`;
        } else if (cmps.hour != null && cmps.hour > 0) {
            return `${cmps.hour}时${cmps.minute ?? 0}分`;
        } else if (cmps.minute != null && cmps.minute > 0) {
            return `${cmps.minute}分`;
        } else {
            return "0";
        }
    },



    // 获取售后列表
    getAfterSales() {
        // 调用函数并传入订单结算时间

        ReIndex({
            act: 'server_config',
            
        }).then(resj => {
            console.log('时间剩余', resj, resj.server_time);

            console.log('当前系统时间', new Date(resj.server_time * 1000));
            getNavigationbar({
                act: 'order_refund_lists',
                p:this.data.currentPage
            }).then(res => {
                console.log('时间', res)
                const timestamp = res.inputtime;
                const date = new Date(timestamp * 1000);

                let systemTimse = resj.server_time; // 假设系统时间为1710127152
                let days = 3; // 假设需要增加3天
                let countdown = this.countdownTime(systemTimse, days);

                res.countdown = countdown;
                res.forEach(element => {
                    const systemTimestamp = resj.server_time; // 系统时间戳

                    const updateTimestamp = parseInt(element.updatetime); // 更新时间戳
                    const comparisonResult = this.calculateTimeDifference(systemTimestamp, updateTimestamp);
                    console.log('倒计时', this.getTiem(updateTimestamp));
                  
                    console.log('comparisonResult', comparisonResult);

                    console.log('===============',this.getRefundStatus(parseInt(element.isclose), parseInt(element.status), parseInt(element.isinter), parseInt(element.refundtype), element))
                    let data = this.getRefundStatus(parseInt(element.isclose), parseInt(element.status), parseInt(element.isinter), parseInt(element.refundtype), element)
                    Object.assign(element, {
                        countdown: countdown,
                        descTime: data.descTime,
                        RefundStatus:  data.statusBlock,
                        comparisult: comparisonResult
                    })
                    
                });
                console.log('获取售后列表', res)
               
                this.setData({
                    orderList: this.data.orderList.concat(res),
                    orderListMian: true
                })
                // this.data.orderList = res
            });
        })
    },
    // 根据提供的判断条件添加退款状态字段
    getRefundStatus(isClose, status, isInter, refundtype, element) {
        console.log('进来啦', isClose, status, isInter)
        let statusBlock = [-1, ""];
        let buyerShippedIndex
        if (isClose == 1) {
            if (status == 6) {
                statusBlock = [6, "已退款"];
            } else if (status == 7) {
                statusBlock = [7, "退款已关闭"];
            } else {
                statusBlock = [20, "退款已关闭"];
            }
        } else {
            switch (status) {
                case 0:
                    statusBlock = [0, "商家处理"];

                    break;
                case 1:
                    if (isInter == 1) {
                        statusBlock = [21, "买家申请小二介入"];
                    } else if (isInter == 2) {
                        statusBlock = [22, "小二正在介入"];
                    } else {
                        statusBlock = [1, "审核失败"];
                    }
                    break;
                case 2:
                    statusBlock = [2, "审核成功"];
                    break;
                case 3:
                    statusBlock = [3, "买家已发货，等待卖家签收"];

                    break;
                case 4:
                    if (isInter == 1) {
                        statusBlock = [21, "买家申请小二介入"];
                    } else if (isInter == 2) {
                        statusBlock = [22, "小二正在介入"];
                    } else if (refundtype == 2) {
                        statusBlock = [4, "请退货"];
                    } else {
                        statusBlock = [4, "卖家拒绝签收"];
                    }
                    break;
                case 5:

                    statusBlock = [5, "卖家已签收"];
                    break;
                case 6:
                    statusBlock = [6, "已退款"];
                    break;
                case 7:
                    statusBlock = [7, "买家撤销"];
                    break;
                default:
                    break;
            }
        }
        console.log('==',statusBlock[0])
        let descTime = this.getRefundStatusText(parseInt(statusBlock[0]), element)
        let data = {
            statusBlock:statusBlock,
            descTime:descTime
        }
        return data;
    },

    getRefundStatusText(status, model) {
        console.log('描述', status, model)
        let timeStr
        let buyerShippedIndex
        switch (status) {
            case 20:
                return "退款关闭：退款已关闭";
            case 21:
                return "待小二处理：客服小二处理中";
            case 22:
                return "小二正在处理";
            case 0:
                console.log('``````````````0')
                timeStr = this.countdownTime(model.updatetime, 3);
                console.log('timeStr', timeStr)
                return "待商家处理：商家将在" + timeStr + "内处理";
            case 1:
                timeStr = this.countdownTime(model.updatetime, 7);
                return "商家审核不通过：原因 " + model.verify_error + ",请于" + timeStr + "内修改申请，超时自动取消";
            case 2:
                if (model.refundtype == 1) {
                    return "审核通过：正等待退款";
                } else {
                    buyerShippedIndex = this.data.steps.findIndex(element => element.text === '填快递单');
                    console.log('buyerShippedIndex', buyerShippedIndex)
                    if (buyerShippedIndex !== -1) {
                        this.data.steps.forEach((element, index) => {
                            if (index <= buyerShippedIndex) {
                                element.status = 1;
                            } else {
                                element.status = 2;
                            }
                        });
                        console.log('走', this.data.steps)
                    }

                    timeStr = this.countdownTime(model.updatetime, 3);
                    return "填写快递单：请于" + timeStr + "内发货并填写快递单，超时自动取消";
                }
                case 3:
                    console.log('+++++++',this.countdownTime(model.updatetime, 7))
                      timeStr = this.countdownTime(model.updatetime, 7);
                      return "待商家收货：商家将在" + timeStr + "内处理";
                case 4:
                    timeStr = this.countdownTime(model.updatetime, 3);
                    return "请退货：商家驳回，原因 " + model.reciever_error + ",请于" + timeStr + "内发货并填写快递单，超时自动取消";
                case 5:
                    return "卖家已签收：正等待退款";
                case 6:
                    return "退款成功：退款成功￥" + model.refundprices;
                case 7:
                    return "退款关闭：您已撤销本次退款申请";

                default:
                    return "退款状态出错啦";
        }
    },
    countdownTime(systemTime, days) {
        // 获取当前时间的时间戳
        let currentTime = new Date().getTime() / 1000;

        // 将系统时间转换为日期对象
        let targetDate = new Date(systemTime * 1000);

        // 在目标日期上增加指定天数
        targetDate.setDate(targetDate.getDate() + days);

        // 计算剩余时间的毫秒数
        let remainingTime = targetDate.getTime() - new Date().getTime();

        // 将毫秒数转换为天、时、分、秒
        let daysLeft = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
        let hoursLeft = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutesLeft = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));

        return daysLeft + "天" + hoursLeft + "时" + minutesLeft + "分";
    },
    /**
     * 跳转
     * @param {*} event 
     */
    enter(event) {
        console.log('e', event)
        let obj = {
            ...event.currentTarget.dataset.value,
            agent_name: event.currentTarget.dataset.value.simplename,
            agent_thumb: event.currentTarget.dataset.value.simplethumb,
            agentid: event.currentTarget.dataset.value.agentid,
            show: true
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    /**
     * 查看退款详情回调函数方法
     */
    handleViewDetail(val) {
        console.log('val', val)
        
        wx.navigateTo({
            url: `/pages/order_refund_detail/index?data=${JSON.stringify(val)}`
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.data.orderList = []
        this.data.currentPage = 1
        // this.getAfterSales()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
        this.getAfterSales()
      
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})